# coding=utf-8
from datetime import datetime
import io
import sys
import json
import requests
import threading
from markdown import markdown
from docx import Document
from docx.shared import Pt
from docx.oxml.ns import qn
from docx.oxml import OxmlElement

def add_heading(document, text, level):
    """添加标题，根据级别设置样式"""
    heading = document.add_heading(level=level)
    run = heading.add_run(text)
    run.font.size = Pt(20 - level)  # 根据级别调整字体大小
    run.font.bold = True

def add_content(document, text):
    """添加内容"""
    paragraph = document.add_paragraph(text)
    paragraph.paragraph_format.first_line_indent = Pt(24)  # 首行缩进
global_thread = {}

#大模型线程并发数量
pool_sema = threading.BoundedSemaphore(20) # 或使用Semaphore方法



from docx import Document
def list_styles(docx_path):
    document = Document(docx_path)
    styles_set = set()  # 使用集合来避免重复的样式名称
    for paragraph in document.paragraphs:
        if paragraph.style:
            print("paragraph.style.name:",paragraph.style.name)
            styles_set.add(paragraph.style.name)
        else:
            print("paragraph:",paragraph)

    return styles_set




from docx import Document


def read_headings(doc_path):
    # 加载文档
    doc = Document(doc_path)
    # 用于存储标题层级的字典
    headings_dict = {}
    # 用于追踪当前标题的父标题的栈
    stack = []

    # 遍历文档中的所有段落
    for para in doc.paragraphs:
        # 获取段落的样式名称
        style_name = para.style.name
        # 检查样式名称是否以"Heading"开头
        if style_name.startswith("Heading"):
            # 获取标题层级
            level = int(style_name.split(" ")[1])
            # 获取标题文本
            text = para.text

            # 创建当前标题的字典
            # current_dict = {text: []}
            current_dict = {text: []}
            if level == 2:
                # Heading 2 作为顶层键
                headings_dict.update(current_dict)
                stack = [current_dict]
            else:
                # 更深层级的标题，需要找到对应的父层级
                # 确保栈的长度与当前层级匹配
                while len(stack) > level - 2:
                    stack.pop()

                # 当前标题的父标题
                parent_dict = stack[-1]
                # 获取父标题的键
                parent_key = list(parent_dict.keys())[0]

                # 如果父标题下还没有子标题列表，则创建一个
                if parent_key not in parent_dict:
                    parent_dict[parent_key] = []

                # 将当前标题添加到父标题的字典中
                # print('parent_dict', parent_dict)
                # print('parent_key', parent_key)
                # print('current_dict', current_dict)
                parent_dict[parent_key].append(current_dict)

                # 更新栈
                stack.append(current_dict)

    return headings_dict


# 示例使用
# doc_path = "./招投标文件生成(data)/24_技术要求_标的1：业务系统2024年第五批采购项目-标.docx"  # 替换为你的文档路径
#全局变量

def dify_chat_streaming(query,number):
    # API端点和API密钥
    # url = 'http://172.16.32.45:11206/v1/chat-messages' #v1/chat-messages'调用聊天框  workflows/run智能体
    url = 'http://192.168.73.129:80/v1/chat-messages' #v1/chat-messages'调用聊天框  workflows/run智能体
    api_key ='app-yDbyAnwoY4KjzX84qGtQMyz6' #'app-ldimOhba65Dq5BlHpPXQaDka'  # 替换为您的实际API密钥

    # 请求头
    headers = {
        'Authorization': f'Bearer {api_key}',
        'Content-Type': 'application/json'
    }

    # 请求数据
    data = {
        "inputs": {},
        "query": query,
        "response_mode": "streaming", #blocking streaming
        "conversation_id": "",
        "user": "abc-123",
            }

    # 将数据转换为JSON字符串
    data_json = json.dumps(data)

    # 发送POST请求
    # response = requests.post(url, headers=headers, data=data_json.encode("utf-8"))
    # response.encoding = 'utf-8'

    answer = ''

    # 发送GET请求，并设置stream=True
    with requests.post(url, headers=headers, data=data_json.encode("utf-8"), stream=True) as r:
        # 检查请求是否成功
        r.raise_for_status()

        # 打印每一行文本
        for line in r.iter_lines():
            # 忽略保持连接的空行
            if line:
                # 解码每一行，因为返回的数据可能是字节串
                line = line.decode('utf-8')
                if 'data: ' in line:
                    data = json.loads(line.replace('data: ', ''))
                    if data['event'] == 'message':
                        # print(data['answer'])
                        answer += data['answer']
    # global_thread[query] = answer
    global_thread[number] = {query: answer}
    return answer
import os
import re
def json_process(data_answ):
    pattern = r'```markdown(.*?)```'
    matches = re.findall(pattern, data_answ, re.DOTALL) #抽取出内容并判断长度
    if matches:
        c_statement = matches[-1]
        # print("\n-------step2查到的对应的内容为：\n", c_statement)
    else:
        c_statement=''
    # decoded_object = json_repair.loads(c_statement)
    # return json.dumps(decoded_object,ensure_ascii=False)
    return c_statement
def docx_title_structure(doc_path):
    current_time = datetime.now()
    f_n = current_time.strftime('%Y%m%d_%H%M%S')

    # f = f'./out_json/{f_n}.html'
    if not os.path.exists('./out_json'):
        os.mkdir('./out_json')
    # file = open(f, 'w', encoding='utf-8')
    headings = read_headings(doc_path)
    # print(headings)
    # 原型界面设计 方案
    number=0
    basic_info_threadpool = []
    top_title = headings['技术实现方案'][6]
    for keys, values in top_title.items():
        # print('keys',keys)
        # file.writelines(f'{keys}\n')
        # basic_info_threadpool.append(
        #     threading.Thread(target=dify_chat_streaming, args=(str(keys))))
        for v_i in values:
            for k_i, v_i in v_i.items():
                # file.writelines(f'{k_i}\n')
                for v_j in v_i:
                    for k_ii, v_ii in v_j.items():
                        # file.writelines(f'{k_ii}\n')
                        # print(k_ii,v_ii)
                        for v_jj in v_ii:
                            for k_iii, v_iii in v_jj.items():
                                # print('v_iii:',v_iii)
                                # file.writelines(f'{k_iii}\n')
                                if v_iii:
                                    # print('最终结果', keys, k_i, k_ii, k_iii)
                                    query=f'{keys},{k_i},{k_ii},{k_iii}'
                                    number+=1
                                    print('======================',[query])
                                    # basic_info_threadpool.append(threading.Thread(target=dify_chat_streaming, args=(query,number)))
                                    global_thread[number] = {query: '</details>'}

                                    for v_jjj in v_iii:
                                        for k_iiii, v_iiii in v_jjj.items():
                                            # file.writelines(f'{k_iiii}\n')
                                            # print('iiii', k_iiii, v_iiii)
                                            # print(keys, k_i, k_ii, k_iii, k_iiii)
                                            query = f'{keys},{k_i},{k_ii},{k_iii},{k_iiii}'
                                            number+=1
                                            print('======================',[query])
                                            # basic_info_threadpool.append(
                                            # threading.Thread(target=dify_chat_streaming, args=(query,number)))
                                            global_thread[number] = {query: '</details>'}
                                #
                                else:
                                    # print('最终结果', keys, k_i, k_ii, k_iii)
                                    query = f'{keys},{k_i},{k_ii},{k_iii}'
                                    print('======================', [query])
                                    # data_answ = dify_chat_streaming(str((query)))
                                    # file.writelines(f'\t{data_answ}\n')
                                    number+=1
                                    # basic_info_threadpool.append(threading.Thread(target=dify_chat_streaming, args=(query,number)))
                                    global_thread[number] = {query: '</details>'}

        # 整一个线程池
        # 启用和阻塞线程
    for th in basic_info_threadpool:
        th.start()
    for th in basic_info_threadpool:
        threading.Thread.join(th)

        # 保存到文件中
    doc = Document()
    # 保存到文件中
    dict_new={}
    global_thread_sorted = sorted(global_thread.keys())
    out_print = {key: global_thread[key] for key in global_thread_sorted}
    for num_keys, values in out_print.items():
        for k_i, v_i in values.items():
            for index,k_ii in enumerate(k_i.split(',')): #k_ii为标题'原型界面设计,智能画像,单企业画像,企业任务进展分析'
                # print(index)
                if index+1 not in dict_new.keys():
                    add_heading(doc, k_ii, index + 1)
                else:
                    if k_ii not in dict_new[index+1]:
                        add_heading(doc, k_ii, index + 1)
                if index+1 not in dict_new.keys():
                    dict_new[index+1]=[]
                    dict_new[index+1].append(k_ii)
                else:
                    # print('dict_new',dict_new)
                    dict_new[index + 1].append(k_ii)
            s = v_i.split('</details>')[-1]+"好东西"
            if '```markdown' in s:
                s_new = json_process(s)
                # file.writelines(f'{s_new}\n')
                add_content(doc, s_new)

            else:
                # file.writelines(f'{s}\n')
                add_content(doc, s)
    doc.save(f'./out_json/output_{f_n}.docx')
    print("HTML文件已保存为./out_json/output_{f_n}.docx")


    # 获取结果
    # 启用线程

        # 合并结果
    # 合并基础信息列表




if __name__=="__main__":

    # 获取文档中的所有样式名称
    # docx_path='./data/24_技术要求_标的1：业务系统2024年第五批采购项目-标.docx'
    # styles_used = list_styles(docx_path)  # 自动获取样式

    # 示例使用
    doc_path = "/media/977GB/virtualbox/24_技术要求_标的1：业务系统2024年第五批采购项目-标.docx"  # 替换为你的文档路径
    docx_title_structure(doc_path)

    # query=''
    # data_answ = dify_chat_streaming(str((query)))